package com.alibaba.citrus.ots.sales.plan.repository;


import com.alibaba.acm.shaded.com.alibaba.metrics.StringUtils;
import com.alibaba.citrus.ots.common.exception.FacadeException;
import com.alibaba.citrus.ots.common.util.DateUtils;
import com.alibaba.citrus.ots.platform.enhance.repository.CustomerRepository;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.pageQueryMonthlyCommerceRequest;
import com.alibaba.citrus.ots.sales.plan.sdo.MonthlyCommerceSDO;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.*;
import com.epoch.app.bcots.sales_plan.monthlyplanofccommerce.dto.LoadListForPageResponse;
import com.epoch.app.bcots.sales_plan.monthlyplanofccommerce.dto.LoadListPageQueryRequest;
import com.epoch.app.bcots.sales_plan.monthlyplanofccommerce.model.MonthlyPlanOfCcommerce;
import com.epoch.app.bcots.sales_plan.monthlyplanofccommerce.service.MonthlyPlanOfCcommerceService;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.otsplatformenhance.domain.customer.dto.CustomerLoadListRequest;
import com.epoch.app.otsplatformenhance.domain.customer.model.Customer;
import com.epoch.app.otsplatformenhance.domain.customer.service.CustomerService;
import com.epoch.app.otsplatformenhance.domain.customersalescope.model.CustomerSaleScope;
import com.epoch.app.otsplatformenhance.dto.request.CustomerBatchRequest;
import com.epoch.app.otsplatformenhance.model.dto.CustomerAddressIndex;
import com.epoch.app.otsplatformenhance.model.dto.PageQueryCustomerScopeRequest;
import com.epoch.app.otsplatformenhance.model.dto.PageQueryCustomerScopeResponse;
import com.epoch.app.otsplatformenhance.opecustomeraddressindex.dto.PageQueryCustomerAddressListRequest;
import com.epoch.app.otsplatformenhance.opecustomeraddressindex.dto.PageQueryCustomerAddressListResponse;
import com.epoch.app.otsplatformenhance.opecustomeraddressindex.service.OpeCustomerAddressIndexService;
import com.epoch.app.otsplatformenhance.sdo.CustomerSDO;
import com.epoch.app.otsplatformenhance.service.OtsPlatformEnhanceService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class MonthlyCommerceRepositoryImpl implements MonthlyCommerceRepository {
    Log log = Log.getLogger(MonthlyCommerceRepositoryImpl.class);

    @Resource
    private MonthlyPlanOfCcommerceService monthlyPlanOfCcommerceService;

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private CustomerRepository customerRepository;

    @Resource
    OtsPlatformEnhanceService otsPlatformEnhanceService;


    @Resource
    CustomerService customerService;

    /**
     * 分页查询
     *
     * @param pageQueryMonthlyCommerceRequest
     * @return
     */
    @Override
    public PageResult<List<MonthlyCommerceSDO>> pageQuery(pageQueryMonthlyCommerceRequest pageQueryMonthlyCommerceRequest) {
        LoadListPageQueryRequest loadListPageQueryRequest = monthlyPlanOfCcommerceQueryConverter(pageQueryMonthlyCommerceRequest);
        if (StringUtils.isNotBlank(pageQueryMonthlyCommerceRequest.getScItemName())
                && CollectionUtils.isEmpty(loadListPageQueryRequest.getOuterIdList())) {
            return PageResult.of(new ArrayList<>(), 0);
        }
        Result<List<MonthlyPlanOfCcommerce>> listResult = monthlyPlanOfCcommerceService.loadListPageQuery(loadListPageQueryRequest);
        Set<String> customerCodes = listResult.getResult().stream().map(MonthlyPlanOfCcommerce::getCustomerCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        CustomerBatchRequest batchRequest = CustomerBatchRequest.builder().codes(Lists.newArrayList(customerCodes)).build();
        List<CustomerSDO> customerSDOS = null;
        try {
            customerSDOS = customerRepository.batchQuery(batchRequest);
        } catch (Exception e) {
            log.info("MonthlyCommerceRepositoryImpl.pageQuery查询客户信息失败" + JSONObject.toJSONString(batchRequest));
            throw new FacadeException("OTS-08-001-01-16-027");
        }
        Map<String, CustomerSDO> customerSDOMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(customerSDOS)) {
            customerSDOMap = customerSDOS.stream().collect(Collectors.toMap(CustomerSDO::getCode, o -> o));
        }
        Map<String, CustomerSDO> finalCustomerSDOMap = customerSDOMap;
        List<MonthlyCommerceSDO> monthlyCommerceSDOS = listResult.getResult().stream().map(monthlyPlanOfCcommerce -> {
            MonthlyCommerceSDO monthlyCommerceSDO = new MonthlyCommerceSDO();
            BeanUtils.copyProperties(monthlyPlanOfCcommerce, monthlyCommerceSDO);
            SearchScItemRequest searchScItemRequest = new SearchScItemRequest();
            Map map = new HashMap();
            List<String> outerIdList = new ArrayList<>();
            List<Integer> statusList = new ArrayList<>();
            outerIdList.add(monthlyCommerceSDO.getOuterId());
            map.put("outerIdList", outerIdList);
            statusList.add(1);
            statusList.add(-1);
            map.put("statusList", statusList);
            searchScItemRequest.setSearchReqDTO(map);
            Result<List<ScItemSDO>> searchScItem = baseDataService.searchScItem(searchScItemRequest);
            List<ScItemSDO> result = searchScItem.getResult();
            if (result == null) {
                throw new FacadeException("OTS-01-005-02-15-001");
            }
            for (ScItemSDO scItemSDO : result) {
                Map features = scItemSDO.getFeatures();
                Object scItemGroupCode = features.get("scItemGroupCode");
                if (Objects.nonNull(scItemGroupCode)) {
                    monthlyCommerceSDO.setScItemGroupCode(scItemGroupCode.toString());
                }
                Object scItemGroupDesc = features.get("scItemGroupDesc");
                if (Objects.nonNull(scItemGroupDesc)) {
                    monthlyCommerceSDO.setScItemGroupDesc(scItemGroupDesc.toString());
                }
                monthlyCommerceSDO.setScItemName(scItemSDO.getTitle());
            }

            monthlyCommerceSDO.setGmtModified(monthlyPlanOfCcommerce.getGmtModified());
            monthlyCommerceSDO.setGmtCreate(monthlyPlanOfCcommerce.getGmtCreate());

            //客户名称
            CustomerSDO customerSDO = finalCustomerSDOMap.get(monthlyPlanOfCcommerce.getCustomerCode());
            if (Objects.nonNull(customerSDO)) {
                monthlyCommerceSDO.setCustomerName(customerSDO.getName());
            }
            //客户名称跟客户编码合在一起
            Map<String, String> customerInfo = new HashMap<>();
            customerInfo.put("title", monthlyCommerceSDO.getCustomerName());
            customerInfo.put("subTitle", "编码：" + monthlyCommerceSDO.getCustomerCode());
            monthlyCommerceSDO.setCustomerInfo(customerInfo);

            Map<String, String> scItemInfo = new HashMap<>();
            scItemInfo.put("title", monthlyCommerceSDO.getScItemName());
            scItemInfo.put("subTitle", "编码：" + monthlyCommerceSDO.getOuterId());
            monthlyCommerceSDO.setScItemInfo(scItemInfo);
            try {
                DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String planTime = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(monthlyPlanOfCcommerce.getPlanTime())), ZoneId.systemDefault()));
                monthlyCommerceSDO.setPlanTime(planTime);
            } catch (Exception e) {
                log.error("时间戳转日期失败");
            }
            try {
                DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy年MM月");
                String formatPlanTime = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(monthlyPlanOfCcommerce.getPlanTime())), ZoneId.systemDefault()));
                monthlyCommerceSDO.setFormatPlanTime(formatPlanTime);
            } catch (Exception e) {
                log.error("时间戳转日期失败");
            }
            //获取平台与销售渠道名称
            extracted(monthlyCommerceSDO);
            queryOrganization(monthlyPlanOfCcommerce, monthlyCommerceSDO);
            monthlyCommerceSDO.setMonthPlannedQuantity(Objects.isNull(monthlyCommerceSDO.getMonthPlannedQuantity()) ? 0 : monthlyCommerceSDO.getMonthPlannedQuantity());
            monthlyCommerceSDO.setMonthReturnCount(Objects.isNull(monthlyCommerceSDO.getMonthReturnCount()) ? 0 : monthlyCommerceSDO.getMonthReturnCount());
            monthlyCommerceSDO.setMonthReviseConfirmCount(Objects.isNull(monthlyCommerceSDO.getMonthReviseConfirmCount()) ? 0 : monthlyCommerceSDO.getMonthReviseConfirmCount());
            monthlyCommerceSDO.setMonthFirstPlannedQuantity(Objects.isNull(monthlyCommerceSDO.getMonthFirstPlannedQuantity()) ? 0 : monthlyCommerceSDO.getMonthFirstPlannedQuantity());
            monthlyCommerceSDO.setMonthFirstReturnCount(Objects.isNull(monthlyCommerceSDO.getMonthFirstReturnCount()) ? 0 : monthlyCommerceSDO.getMonthFirstReturnCount());
            monthlyCommerceSDO.setMonthFirstReviseConfirmCount(Objects.isNull(monthlyCommerceSDO.getMonthFirstReviseConfirmCount()) ? 0 : monthlyCommerceSDO.getMonthFirstReviseConfirmCount());
            monthlyCommerceSDO.setMonthMiddlePlannedQuantity(Objects.isNull(monthlyCommerceSDO.getMonthMiddlePlannedQuantity()) ? 0 : monthlyCommerceSDO.getMonthMiddlePlannedQuantity());
            monthlyCommerceSDO.setMonthMiddleReturnCount(Objects.isNull(monthlyCommerceSDO.getMonthMiddleReturnCount()) ? 0 : monthlyCommerceSDO.getMonthMiddleReturnCount());
            monthlyCommerceSDO.setMonthMiddleReviseConfirmCount(Objects.isNull(monthlyCommerceSDO.getMonthMiddleReviseConfirmCount()) ? 0 : monthlyCommerceSDO.getMonthMiddleReviseConfirmCount());
            monthlyCommerceSDO.setMonthLastPlannedQuantity(Objects.isNull(monthlyCommerceSDO.getMonthLastPlannedQuantity()) ? 0 : monthlyCommerceSDO.getMonthLastPlannedQuantity());
            monthlyCommerceSDO.setMonthLastReturnCount(Objects.isNull(monthlyCommerceSDO.getMonthLastReturnCount()) ? 0 : monthlyCommerceSDO.getMonthLastReturnCount());
            monthlyCommerceSDO.setMonthLastReviseConfirmCount(Objects.isNull(monthlyCommerceSDO.getMonthLastReviseConfirmCount()) ? 0 : monthlyCommerceSDO.getMonthLastReviseConfirmCount());
            //计算五日调整量
            monthlyCommerceSDO.setMonthSummaryCount(monthlyCommerceSDO.getMonthReviseConfirmCount() - monthlyCommerceSDO.getMonthReturnCount());
            monthlyCommerceSDO.setMonthFirstSummaryCount(monthlyCommerceSDO.getMonthFirstReviseConfirmCount() - monthlyCommerceSDO.getMonthFirstReturnCount());
            monthlyCommerceSDO.setMonthMiddleSummaryCount(monthlyCommerceSDO.getMonthMiddleReviseConfirmCount() - monthlyCommerceSDO.getMonthMiddleReturnCount());
            monthlyCommerceSDO.setMonthLastSummaryCount(monthlyCommerceSDO.getMonthLastReviseConfirmCount() - monthlyCommerceSDO.getMonthLastReturnCount());
            return monthlyCommerceSDO;
        }).collect(Collectors.toList());
        return PageResult.of(monthlyCommerceSDOS, listResult.getTotal());
    }

    private void extracted(MonthlyCommerceSDO monthlyCommerceSDO) {
        //销售渠道名称,电商平台获取  暂时赋值测试值 TODO (需要查询收货地址获取唯一值)
        PageQueryCustomerScopeRequest scopeRequest = new PageQueryCustomerScopeRequest();
        //电商平台 销售渠道名称 根据客户编码+货品组+销售组织编码+业务渠道固定20 找到唯一的客户售达方 进行展示
        if (StringUtils.isNotBlank(monthlyCommerceSDO.getCustomerCode())) {
            scopeRequest.setCustomerCode(monthlyCommerceSDO.getCustomerCode());
        }
        if (StringUtils.isNotBlank(monthlyCommerceSDO.getScItemGroupCode())) {
            scopeRequest.setItemGroup(monthlyCommerceSDO.getScItemGroupCode());
        }
        if (StringUtils.isNotBlank(monthlyCommerceSDO.getOrgSaleOrganizationCode())) {
            scopeRequest.setOrgSaleOrganizationCode(monthlyCommerceSDO.getOrgSaleOrganizationCode());
        }
        scopeRequest.setChannelCode("20");
        PageQueryCustomerScopeResponse pageQueryCustomerScopeResponse = otsPlatformEnhanceService.pageQueryCustomerScope(scopeRequest);
        if (Objects.isNull(pageQueryCustomerScopeResponse) || CollectionUtils.isEmpty(pageQueryCustomerScopeResponse.getResult())) {
            log.info("pageQueryCustomerScopeResponse查询失败");
            return;
        }
        Map o = (Map) pageQueryCustomerScopeResponse.getResult().get(0);
        if (Objects.nonNull(o.get("outOrgSalesChannelName"))) {
            monthlyCommerceSDO.setOrgSalesChannelName(String.valueOf(o.get("outOrgSalesChannelName")));
            monthlyCommerceSDO.setOrgSalesChannelCode(String.valueOf(o.get("orgSaleChannelCode")));
        }
        if (Objects.nonNull(o.get("commercePlatform"))) {
            monthlyCommerceSDO.setCommercePlatform(String.valueOf(o.get("commercePlatform")));
            monthlyCommerceSDO.setCommercePlatformCode(String.valueOf(o.get("commercePlatformCode")));
        }
    }

    private void queryOrganization(MonthlyPlanOfCcommerce monthlyPlanOfCcommerce, MonthlyCommerceSDO monthlyCommerceSDO) {
        BaselineGetOrganizationByIds2Request baselineGetOrganizationByIds2Request = new BaselineGetOrganizationByIds2Request();
        baselineGetOrganizationByIds2Request.setIds(Lists.newArrayList(monthlyPlanOfCcommerce.getOrgBusinessCode()));
        BaselineGetOrganizationByIds2Response baselineGetOrganizationByIds2Response = baseDataService.baselineGetOrganizationByIds2(baselineGetOrganizationByIds2Request);
        if (baselineGetOrganizationByIds2Response != null || CollectionUtils.isNotEmpty(baselineGetOrganizationByIds2Response.getResult())) {
            baselineGetOrganizationByIds2Response.getResult().stream().forEach(organizationSDO -> {
                monthlyCommerceSDO.setOrgBusinessName(organizationSDO.getName());
            });
        }
    }


    private LoadListPageQueryRequest monthlyPlanOfCcommerceQueryConverter(pageQueryMonthlyCommerceRequest pageQueryMonthlyCommerceRequest) {
        LoadListPageQueryRequest loadListRequest = new LoadListPageQueryRequest();
        BeanUtils.copyProperties(pageQueryMonthlyCommerceRequest, loadListRequest);
        if (StringUtil.isNotEmpty(pageQueryMonthlyCommerceRequest.getOuterId())) {
            loadListRequest.setOuterId(pageQueryMonthlyCommerceRequest.getOuterId());
        }
        if (StringUtil.isNotEmpty(pageQueryMonthlyCommerceRequest.getCustomerCode())) {
            loadListRequest.setCustomerCodeList(Lists.newArrayList(pageQueryMonthlyCommerceRequest.getCustomerCode()));
        }
        if (StringUtil.isNotEmpty(pageQueryMonthlyCommerceRequest.getPlanTime())) {
            loadListRequest.setPlanTime(DateUtils.dateToStamp(pageQueryMonthlyCommerceRequest.getPlanTime() + "-01 00:00:00"));
        }
        if (StringUtil.isNotEmpty(pageQueryMonthlyCommerceRequest.getPlanStartTime())) {
            loadListRequest.setPlanStartTime(DateUtils.dateToStamp(pageQueryMonthlyCommerceRequest.getPlanStartTime() + "-01 00:00:00"));
        }
        if (StringUtil.isNotEmpty(pageQueryMonthlyCommerceRequest.getPlanEndTime())) {
            loadListRequest.setPlanEndTime(DateUtils.dateToStamp(pageQueryMonthlyCommerceRequest.getPlanEndTime() + "-01 00:00:00"));
        }
        //查货品名称
        SearchScItemRequest searchScItemRequest = new SearchScItemRequest();
        Map map = new HashMap();
        if (StringUtils.isNotBlank(pageQueryMonthlyCommerceRequest.getScItemName())) {
            map.put("title", pageQueryMonthlyCommerceRequest.getScItemName());
            searchScItemRequest.setSearchReqDTO(map);
            searchScItemRequest.setPageSize(2000);
            searchScItemRequest.setPageNum(1);
            Result<List<ScItemSDO>> listResult = baseDataService.searchScItem(searchScItemRequest);
            if (null == listResult || CollectionUtils.isEmpty(listResult.getResult())) {
                loadListRequest.setOuterIdList(null);
                return loadListRequest;
            }
            List<String> outerIdList = listResult.getResult().stream().map(ScItemSDO::getOuterId).collect(Collectors.toList());
            loadListRequest.setOuterIdList(outerIdList);
        }

        //查客户名称
        List<String> customers = new ArrayList<>();
        CustomerLoadListRequest customerLoadListRequest = new CustomerLoadListRequest();
        if (StringUtils.isNotBlank(pageQueryMonthlyCommerceRequest.getCustomerName())) {
            customerLoadListRequest.setName(pageQueryMonthlyCommerceRequest.getCustomerName());
            Result<List<Customer>> listResult = customerService.loadCustomerList(customerLoadListRequest);
            if (listResult != null || CollectionUtils.isNotEmpty(listResult.getResult())) {
                listResult.getResult().stream().forEach(it -> {
                    if (StringUtils.isNotBlank(it.getCode())) {
                        customers.add(it.getCode());
                        loadListRequest.setCustomerCodeList(customers);
                    }
                });
            }
        }
        return loadListRequest;
    }
}
